//防抖
export function debounce(func, wait, immediate) {
  let timeout
  console.log('debounce')
  return function() {
    let context = this,
      args = arguments
    let later = function() {
      timeout = null
      if (!immediate) {
        func.apply(context, args)
      }
    }

    let callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}

//获取元素位置
export function getElementOption(obj) {
  var curleft = 0,
    curtop = 0
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while ((obj = obj.offsetParent)) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return { x: curleft, y: curtop }
}
//平滑滚动
//container 需要scroll的元素，scrollPos 需要滚动的距离，repeatTimes 需要滚动的次数
export function scrollSmoothly(container, scrollPos, repeatTimes) {
  console.log(repeatTimes, 'repeatTimes---------')
  if (repeatTimes) {
    container.scrollBy(0, 10)
  } else {
    return
  }
  repeatTimes--
  setTimeout(scrollSmoothly(scrollPos, repeatTimes), 10)
}
export function download(res, type) {
  const typeArr = {
    jpg: 'image/pjpeg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    gif: 'image/gif',
    doc: 'application/msword',
    docx:
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    xls: 'application/vnd.ms-excel',
    pptx:
      'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    ppt: 'application/vnd.ms-powerpoint',
    pdf: 'application/pdf',
    word: 'application/msword',
    excel: 'application/vnd.ms-excel;charset=utf-8',
  }

  const blob = new Blob([res], {
    type: typeArr[type],
  })
}
export function setLocalItem(key, value) {
  let APP_KEY = 'music_local_list'
  var localString = localStorage.getItem(APP_KEY)
    ? localStorage.getItem(APP_KEY)
    : '{}'
  var localObj = JSON.parse(localString)
  localObj[key] = value
  localStorage.setItem(APP_KEY, JSON.stringify(localObj))
}
export function getLocalItem(key) {
  let APP_KEY = 'music_local_list'
  var localString = localStorage.getItem(APP_KEY)
    ? localStorage.getItem(APP_KEY)
    : '{}'
  var localObj = JSON.parse(localString)
  return localObj[key]
}
/**
 * DataUrl转为File
 * @param {String} dataUrl - dataUrl地址
 * @param {String} fileName - file文件名
 */
export function dataURLtoFile(dataUrl, fileName) {
  var arr = dataUrl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}
